import CustomToolTipVue from './CustomToolTip.vue'
import Vue from 'vue'

const CustomToolTipConstructor = Vue.extend(CustomToolTipVue)

let currentMsg, instance

const initInstance = () => {
  instance = new CustomToolTipConstructor({
    el: document.createElement('div')
  }).$mount()
}

const showNextMsg = () => {
  if (!instance) {
    initInstance()
  }

  if (!instance.visible) {
    for (let prop in currentMsg) {
      if (currentMsg.hasOwnProperty(prop)) {
        instance[prop] = currentMsg[prop]
      }
    }
    document.body.appendChild(instance.$el)

    Vue.nextTick(() => {
      instance.visible = true
    })
  }
}

const CustomToolTip = function (options) {
  if (typeof options === 'string') {
    options = {
      text: options
    }
  }
  currentMsg = options

  showNextMsg()
}

CustomToolTip.show = (options) => {
  return CustomToolTip(options)
}

CustomToolTip.close = () => {
  if (instance) {
    instance.visible = false
    currentMsg = null
  }
}

CustomToolTip.install = function (Vue) {
  Vue.component(CustomToolTip.name, CustomToolTip)
}

export default CustomToolTip
export { CustomToolTip }
